<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\controller\BaseController;
use app\common\model\Attachment as AttachmentModel;
use app\common\library\storage\Storage;
use think\facade\Filesystem;
use think\File;
use general\Random;
use think\Facade\Config;

class Upload extends BaseController
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    /**
     * @var AttachmentModel
     */
    private $AttachmentModel;

    public function initialize()
    {
        parent::initialize();

        $this->AttachmentModel = new AttachmentModel;

    }

    public function index()
    {
        // 上传的文件
        $file = request()->file('file');

        $type = request()->param('type', 'local', 'trim');
        // 判断配置是否存在
        if (is_null(Filesystem::getDiskConfig($type))) {
            $type = 'local';
        }
        // 实例化存储驱动
        $storage = (new Storage())->driver($type);
        if ($type == 'local') {
            $storage->setDisk('public');
        }
        //上传文件保存路径
        $savekey = get_file_savekey($file);

        //上传
        $res = $storage
            ->setUploadFile($file)
            //->setRootDirName('image') //设置上传的目录
            ->setRule('md5')
            ->setHashName($savekey) //可以注释掉，使用系统默认的生成规则
            ->upload();
        if (!$res) {
            return $this->error('错误信息：' . $storage->getError());
        }
        // 文件信息
        $fileInfo = $storage->getSaveFileInfo();

        if ($fileInfo['storage'] == 'local') {
            $fileInfo['domain'] = '';
            $fileInfo['file_path'] = $fileInfo['file_url'];
            $fileInfo['file_url'] = request()->domain() . $fileInfo['file_url'];
        } else {
            //$fileInfo['file_path'] = '/' . $fileInfo['file_path'];
        }

        $arrData = [
            'admin_id' => $this->auth->id,
            'storage' => $fileInfo['storage'],
            'domain' => $fileInfo['domain'],
            'url' => $fileInfo['file_url'],
            'path' => $fileInfo['file_path'],
            'filename' => $fileInfo['file_name'],
            'filesize' => $fileInfo['file_size'],
            'suffix' => $fileInfo['file_ext'],
            'mimetype' => $fileInfo['file_type'],
            'sha1' => $fileInfo['file_sha1'],
        ];
        $this->AttachmentModel->save($arrData);

        // 图片上传成功
        return json([
            'url' => $fileInfo['file_url'],
        ]);
    }
}
